package com.zw.utils;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

/**
 * @author zhuzhe
 * @email zhuzhe_mail@163.com
 * @date 2025-02-17 16:31
 */
public class RSAUtils {

    public static void main(String[] args) throws Exception {
        // 示例：假设这些是从前端传来的密钥（Base64 编码）
        String base64PublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAiRvMULctb2vSZiUmalr96KYu354jPYSmxrvG/DwTH466iuuydlU10VLsDITg14Z7WYXTmONkhnvbxg4JNJ9PDCx7yax2k2Mbm8ZKD2E2v5ltpkEQka0F5ab9kG3HYhlvPPWK5CBExGCPWXOyxms8Rz/WowPsFlWDdcFsrbpJtlrt1dRGR4hW/q3EcvGB6ZHCJZvli768vYE7i4t9i4P6ggABCWxl0KZ+X5wN1xYr0Zx/L3g/CJjZUupklFbRdn5nbzKNo2XGOQvlPJ6COpNvL9lzxBN9Q3ubY11wPmlgo6qXErMOOMhkPzElw3ZtceEhDBd+ieZefkq/pEo0KdI01QIDAQAB";
        String base64PrivateKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCJG8xQty1va9JmJSZqWv3opi7fniM9hKbGu8b8PBMfjrqK67J2VTXRUuwMhODXhntZhdOY42SGe9vGDgk0n08MLHvJrHaTYxubxkoPYTa/mW2mQRCRrQXlpv2QbcdiGW889YrkIETEYI9Zc7LGazxHP9ajA+wWVYN1wWytukm2Wu3V1EZHiFb+rcRy8YHpkcIlm+WLvry9gTuLi32Lg/qCAAEJbGXQpn5fnA3XFivRnH8veD8ImNlS6mSUVtF2fmdvMo2jZcY5C+U8noI6k28v2XPEE31De5tjXXA+aWCjqpcSsw44yGQ/MSXDdm1x4SEMF36J5l5+Sr+kSjQp0jTVAgMBAAECggEAd0Nd60wbUpNYlg90pgj2WlvL5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rN4+f1fdZiKhzJPjwckx0/ZPpKzJed6YLFIUf3GL1S9ULNJ/4n8gtVyJfyMRMZJdDcJSL4QtIFXqXnsxk0OU40p3oqA796E3PAUVTqPC3wOmB1jhcKH8";
        // 生成公钥和私钥对象
        PublicKey publicKey = getPublicKey(base64PublicKey);
        PrivateKey privateKey = getPrivateKey(base64PrivateKey);

        // 加密示例
        String dataToEncrypt = "111111";
        String encryptedData = encrypt(dataToEncrypt, publicKey);
        System.out.println("Encrypted Data (Base64): " + encryptedData);

        // 解密示例
        String decryptedData = decrypt(encryptedData, privateKey);
        System.out.println("Decrypted Data: " + decryptedData);
    }

    // 读取 RSA 公钥（这应该是前端使用的公钥）
    public static PublicKey getPublicKey(String base64PublicKey) throws Exception {
        byte[] decodedKey = Base64.getDecoder().decode(base64PublicKey);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey));
    }

    // 读取 RSA 私钥（后端使用的私钥）
    public static PrivateKey getPrivateKey(String base64PrivateKey) throws Exception {
        byte[] decodedKey = Base64.getDecoder().decode(base64PrivateKey);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(decodedKey));
    }

    // 加密方法：使用公钥加密
    public static String encrypt(String data, PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); // 使用 PKCS1 填充方式
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);

        // RSA 加密最大输入长度受密钥长度限制，对于 2048 位密钥，最大可以加密 245 字节
        byte[] encryptedData = cipher.doFinal(data.getBytes());

        // 返回 Base64 编码后的密文
        return Base64.getEncoder().encodeToString(encryptedData);
    }

    // 解密
    public static String decrypt(String encryptedText, PrivateKey privateKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
        return new String(decryptedBytes);
    }

}
